package com.learning.platform.service;

import com.learning.platform.dto.*;
import com.learning.platform.entity.*;
import com.learning.platform.enums.PostType;
import com.learning.platform.exception.BusinessException;
import com.learning.platform.repository.*;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CommunityService {
    
    private final PostRepository postRepository;
    private final CommentRepository commentRepository;
    private final UserRepository userRepository;
    private final CourseRepository courseRepository;
    // 回滚通知功能：移除依赖
    
    public CommunityService(PostRepository postRepository,
                           CommentRepository commentRepository,
                           UserRepository userRepository,
                           CourseRepository courseRepository) {
        this.postRepository = postRepository;
        this.commentRepository = commentRepository;
        this.userRepository = userRepository;
        this.courseRepository = courseRepository;
    }
    
    public PostResponse createPost(PostRequest request, Long userId) {
        Post post = new Post();
        BeanUtils.copyProperties(request, post);
        post.setUserId(userId);
        
        post = postRepository.save(post);
        return convertToPostResponse(post);
    }
    
    public Page<PostResponse> getPostsByCourse(Long courseId, PostType postType, String keyword, Pageable pageable) {
        Page<Post> posts;
        if (postType != null) {
            posts = postRepository.findByCourseIdAndPostTypeAndStatus(courseId, postType, 
                com.learning.platform.enums.PostStatus.PUBLISHED, pageable);
        } else {
            posts = postRepository.findByCourseIdAndStatus(courseId, 
                com.learning.platform.enums.PostStatus.PUBLISHED, pageable);
        }
        return posts.map(this::convertToPostResponse);
    }
    
    public PostResponse getPost(Long id) {
        Post post = postRepository.findById(id)
            .orElseThrow(() -> new BusinessException("帖子不存在"));
        
        // 增加浏览量
        post.setViewCount(post.getViewCount() + 1);
        postRepository.save(post);
        
        return convertToPostResponse(post);
    }
    
    public PostResponse updatePost(Long id, PostRequest request, Long userId) {
        Post post = postRepository.findById(id)
            .orElseThrow(() -> new BusinessException("帖子不存在"));
        
        if (!post.getUserId().equals(userId)) {
            throw new BusinessException("无权限修改此帖子");
        }
        
        BeanUtils.copyProperties(request, post, "id", "userId", "createdAt", "viewCount", "likeCount", "commentCount");
        post = postRepository.save(post);
        return convertToPostResponse(post);
    }
    
    public void deletePost(Long id, Long userId) {
        Post post = postRepository.findById(id)
            .orElseThrow(() -> new BusinessException("帖子不存在"));
        
        if (!post.getUserId().equals(userId)) {
            throw new BusinessException("无权限删除此帖子");
        }
        
        post.setStatus(com.learning.platform.enums.PostStatus.DELETED);
        postRepository.save(post);
    }
    
    public CommentResponse createComment(CommentRequest request, Long userId) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(request, comment);
        comment.setUserId(userId);
        
        comment = commentRepository.save(comment);
        
        // 更新帖子评论数
        Post post = postRepository.findById(request.getPostId()).orElse(null);
        if (post != null) {
            post.setCommentCount(post.getCommentCount() + 1);
            postRepository.save(post);
        }
        
        // 回滚：不再发送通知
        
        return convertToCommentResponse(comment);
    }
    
    public Page<CommentResponse> getCommentsByPost(Long postId, Pageable pageable) {
        Page<Comment> comments = commentRepository.findByPostIdAndParentIdIsNull(postId, pageable);
        return comments.map(this::convertToCommentResponse);
    }
    
    public void toggleLike(String targetType, Long targetId, Long userId) {
        // 简化实现，实际应该检查是否已点赞并切换状态
        if ("POST".equals(targetType)) {
            Post post = postRepository.findById(targetId).orElse(null);
            if (post != null) {
                post.setLikeCount(post.getLikeCount() + 1);
                postRepository.save(post);
                
                // 回滚：不再发送通知
            }
        } else if ("COMMENT".equals(targetType)) {
            Comment comment = commentRepository.findById(targetId).orElse(null);
            if (comment != null) {
                comment.setLikeCount(comment.getLikeCount() + 1);
                commentRepository.save(comment);
            }
        }
    }
    
    public void markAsSolution(Long commentId, Long userId) {
        Comment comment = commentRepository.findById(commentId)
            .orElseThrow(() -> new BusinessException("评论不存在"));
        
        // 检查权限：帖子作者可以标记解答
        Post post = postRepository.findById(comment.getPostId()).orElse(null);
        if (post == null || !post.getUserId().equals(userId)) {
            throw new BusinessException("无权限标记解答");
        }
        
        comment.setIsSolution(true);
        commentRepository.save(comment);
        
        // 标记帖子为已解决
        post.setIsSolved(true);
        postRepository.save(post);
        
        // 回滚：不再发送通知
    }
    
    private PostResponse convertToPostResponse(Post post) {
        PostResponse response = new PostResponse();
        BeanUtils.copyProperties(post, response);
        
        // 获取用户信息
        userRepository.findById(post.getUserId())
            .ifPresent(user -> {
                response.setUserName(user.getUsername());
                response.setUserAvatar(user.getAvatarUrl());
            });
        
        // 获取课程名称
        courseRepository.findById(post.getCourseId())
            .ifPresent(course -> response.setCourseName(course.getTitle()));
        
        return response;
    }
    
    private CommentResponse convertToCommentResponse(Comment comment) {
        CommentResponse response = new CommentResponse();
        BeanUtils.copyProperties(comment, response);
        
        // 获取用户信息
        userRepository.findById(comment.getUserId())
            .ifPresent(user -> {
                response.setUserName(user.getUsername());
                response.setUserAvatar(user.getAvatarUrl());
            });
        
        return response;
    }
}
